package com.windea.study.kotlin.jvm.crypt.sections

import com.windea.study.kotlin.jvm.crypt.extensions.*
import javax.crypto.*
import javax.crypto.spec.*

object Crypt {
	fun encrypt(input: ByteArray, key: ByteArray, transformation: String = "AES"): ByteArray {
		val keySpec = SecretKeySpec(key, transformation)
		val cipher = Cipher.getInstance(transformation)
		//使用CBC模式时，这里需要添加额外参数
		if("CBC" in transformation) {
			val iv = IvParameterSpec(key)
			cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv)
		} else {
			cipher.init(Cipher.ENCRYPT_MODE, keySpec)
		}
		return cipher.doFinal(input)
	}
	
	fun encrypt(input: String, key: String, transformation: String = "AES"): String {
		//需要对结果进行base64编码
		return encrypt(input.encodeToByteArray(), key.encodeToByteArray(), transformation).encodeBase64().decodeToString()
	}
	
	fun decrypt(input: ByteArray, key: ByteArray, transformation: String = "AES"): ByteArray {
		val keySpec = SecretKeySpec(key, transformation)
		val cipher = Cipher.getInstance(transformation)
		//使用CBC模式时，这里需要添加额外参数
		if("CBC" in transformation) {
			val iv = IvParameterSpec(key)
			cipher.init(Cipher.DECRYPT_MODE, keySpec, iv)
		} else {
			cipher.init(Cipher.DECRYPT_MODE, keySpec)
		}
		return cipher.doFinal(input)
	}
	
	fun decrypt(input: String, key: String, transformation: String = "AES"): String {
		//需要对输入进行base64解码
		return decrypt(input.encodeToByteArray().decodeBase64(), key.encodeToByteArray(), transformation).decodeToString()
	}
}
